<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js布局</title>
    <style>
        .item{
            width: 100px;
            height: 100px;
            margin: 10px;
            background-color: palegoldenrod;
        }
        .wrap{
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div class="cols">
        <button class="three">3列</button>
        <button class="four">4列</button>
        <button class="five">5列</button>
    </div>
    <div class="wrap">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>

    <script>
        var itemw = 120;
        var btns = document.getElementsByTagName('button');
        var items = document.getElementsByClassName('item');
        btns[0].onclick = function(){
            colsFlex(3);
        }
        btns[1].onclick = function(){
            colsFlex(4);
        }
        btns[2].onclick = function(){
            colsFlex(5);
        }
        function colsFlex(colNum){
            //浮动
            for(var i = 0;i < items.length ; i++){
            items[i].style.float = 'left';
            items[0].parentNode.style.width = (colNum*itemw)+'px';
            }
            //定位
            for(var i = 0; i < items.length ; i++){
            var row = parseInt(i / colNum);
            var col = parseInt(i % colNum);
            items[i].style.position = 'absolute';
            items[i].style.top = (row * items[i].offsetHigth)+'px';
            items[i].style.left = (col * items[i].offsetWigth)+'px';
        }
        }
        //
        
    </script>
</body>
</html>